import Vue from 'vue'
import axios from 'axios'
// import store from '../store'
import router from '../router'
import { Notice, Message } from 'iview'
import { read, clearMulti } from '../storage/index'
import {
  STORE_KEY_USERNAME,
  STORE_KEY_ACCESS_TOKEN,
  STORE_KEY_REALNAME,
  STORE_KEY_ID,
  STORE_KEY_SESSION,
  STORE_KEY_ORGID
} from '../storage/constants'
// Vue.http.options.emulateJSON = true
// Vue.http.options.root = '/api'

const requestMap = {}

// response interceptor
axios.interceptors.request.use(request => {
  let key
  // abort the same post request
  if (/POST|PUT|DELETE/.test(request.method)) {
    key = `${request.method}${request.url}${JSON.stringify(request.body)}`
    // abort the existed request
    if (key && requestMap[key]) {
      key = null
      setTimeout(() => {
        request.abort()
      })
    } else {
      requestMap[key] = request
    }
  }

   //if (store.getters.loggedIn) {
  // if logged in, add the token to the header
  request.headers.common.Authorization = `${read('accessToken')}`
   //}
  return request
})

axios.interceptors.response.use(response => {
  // delete current request in the map
  const request = response.request
  let key
  if (/POST|PUT|DELETE/.test(request.method)) {
    key = `${request.method}${request.url}${JSON.stringify(request.body)}`
    delete requestMap[key]
  }
  // don't handler for login page
  // other errors
  if (!response.ok) {
    // Notice.error({
    //   title: Vue.t('http.error.others'),
    //   desc: response.data
    // })
  }
  return response
}, (err) => {
   /* router.replace({
        path: '/login',
        // param: {redirect: router.currentRoute.fullPath}
    })*/
  if (err.response.status === 307) {
  }
  if (err.response.status === 401) {
    Notice.error({
      title: Vue.t('http.error.E401')
    })
    return err.response
  }
  if (err.response.status === 403) {
    Notice.error({
      title: Vue.t('http.error.E403')
    })
    return err.response
  }
  if (err.response.status === 404) {
    // Notice.error({
    //   // title: Vue.t('http.error.E404')
    // })
    return err.response
  }
  if (err.response.status === 500) {
      if (err.response.data.code=== 11000||err.response.data.code=== '11000'){
          Message.warning('登录失效，请重新登录')
          if (router.currentRoute.fullPath!=='/login'||router.currentRoute.fullPath!=='/logout') {
              sessionStorage.setItem('myPrevPath', router.currentRoute.fullPath)
          }
          router.push({path: '/login'})
          // router.push({path: '/login', params: {redirect: router.currentRoute.fullPath}  }) // 先 / 再  /login,会丢掉路由参数
      }
      return err.response
  }
    return err.response
})
